//
//  CustomLineView.m
//  HLRecord
//
//  Created by XTW on 2022/11/18.
//

#import "CustomLineView.h"

@interface CustomLineView()<UIGestureRecognizerDelegate> {
    
}
@property (nonatomic, strong) UIPanGestureRecognizer *gestureRecognizer;
@property (nonatomic, assign) CGPoint startPoint;

@end

@implementation CustomLineView
- (instancetype)initCustomView:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        UIImageView *line = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 1, frame.size.height)];
        [line setBackgroundColor:rgba(236, 94, 101, 1)];
        [line setCenter:CGPointMake(frame.size.width/2.0, frame.size.height/2.0)];
        [self addSubview:line];
        UIImageView *dot1 = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 6, 6)];
        dot1.layer.masksToBounds = YES;
        dot1.layer.cornerRadius = 3.0f;
        [dot1 setBackgroundColor:rgba(236, 94, 101, 1)];
        [dot1 setCenter:CGPointMake(frame.size.width/2.0, 3)];
        [self addSubview:dot1];
        UIImageView *dot2 = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 6, 6)];
        dot2.layer.masksToBounds = YES;
        dot2.layer.cornerRadius = 3.0f;
        [dot2 setBackgroundColor:rgba(236, 94, 101, 1)];
        [dot2 setCenter:CGPointMake(frame.size.width/2.0, frame.size.height - 3)];
        [self addSubview:dot2];
        
        
        UIPanGestureRecognizer *gestureRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handlePan:)];
        [self addGestureRecognizer:gestureRecognizer];
        _gestureRecognizer = gestureRecognizer;
        _gestureRecognizer.enabled = NO;
    }
    return self;
}

- (BOOL)isEnabled
{
    return _gestureRecognizer.isEnabled;
}

- (void)setEnabled:(BOOL)enabled
{
    _gestureRecognizer.enabled = enabled;
}

- (void)handlePan:(UIPanGestureRecognizer *)gestureRecognizer
{
    if (gestureRecognizer.state == UIGestureRecognizerStateBegan) {
        self.startPoint = self.center;
    } else if (gestureRecognizer.state == UIGestureRecognizerStateChanged) {
        CGPoint translation = [gestureRecognizer translationInView:self.superview];
        CGPoint point = self.center;
        point.x = self.startPoint.x+translation.x;
        if (point.x <= self.minX) {
            point.x = self.minX;
        } else if (point.x >= self.maxX){
            point.x = self.maxX;
        }
        [self setCenter:point];

        if ([self.delegate respondsToSelector:@selector(lineDidChangeScale:)]) {
            [self.delegate lineDidChangeScale:(point.x - self.minX)/(self.maxX - self.minX)];
        }
    } else if (gestureRecognizer.state == UIGestureRecognizerStateEnded || gestureRecognizer.state == UIGestureRecognizerStateCancelled) {
        
    }
}
@end
